#include "config_view.h"
#include "ui_config_view.h"
#include "edit_node_dialog.h"
#include <QFile>
#include <QDebug>
#include <QPushButton>
#include <QMenu>
#include <QContextMenuEvent>
#include <QKeyEvent>
#include <QMessageBox>
#include "dealer_handler.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QVariant>
#include "database_manager.h"
#include <QObject>
#include "state_group.h"

ConfigView::ConfigView(SearchTreeWidget *search_tree, QWidget *parent)
    : QWidget(parent),
      ui_(new Ui::ConfigView),
      dealer_handler_(DealerHandler::getInstance()),
      search_tree_(search_tree)
{
    ui_->setupUi(this);

    ui_->remoteTab->setSearchTreeWidget(search_tree_);

    // 连接搜索树形控件项点击信号
    connect(search_tree_, &SearchTreeWidget::itemClicked,
            this, &ConfigView::onSearchTreeWidgetItemClicked);
    connect(search_tree_, &SearchTreeWidget::addNodeRequested, this, &ConfigView::onAddNodeRequested);

    // 替换原有的树形控件
    QVBoxLayout *layout = new QVBoxLayout(ui_->leftContainer);
    layout->setContentsMargins(0, 0, 0, 0);

    // 连接网络消息信号
    connect(dealer_handler_, &DealerHandler::messageReceived, this, &ConfigView::onNetworkMessageReceived);

    // 生成告警策略
    connect(ui_->saveButton, &QPushButton::clicked, this, &ConfigView::onGenerateAlarmStrategyButtonClicked);

    // 下装按钮点击信号
    connect(ui_->downloadButton, &QPushButton::clicked, this, &ConfigView::onDownloadButtonClicked);

    // 初始化告警规则
    loadAlarmRules();

    // 更新显示
    renderAlarmRulesToTable();

    // 设置表格列宽
    QHeaderView *strategy_table_header = ui_->alarmStrategyTable->horizontalHeader();
    strategy_table_header->setStretchLastSection(false);
    strategy_table_header->setDefaultSectionSize(100);
    strategy_table_header->setSectionResizeMode(0, QHeaderView::Fixed);
    strategy_table_header->setSectionResizeMode(1, QHeaderView::Stretch);
    strategy_table_header->setSectionResizeMode(2, QHeaderView::Fixed);
    ui_->alarmStrategyTable->setColumnWidth(0, 60);    // 序号列宽60
    ui_->alarmStrategyTable->setColumnWidth(2, 80);    // 操作列宽80
    ui_->alarmStrategyTable->setColumnHidden(3, true); // 隐藏时间间隔列

    // 设置表格基本属性
    ui_->alarmStrategyTable->setShowGrid(true);
    ui_->alarmStrategyTable->verticalHeader()->setVisible(false); // 隐藏垂直表头
    ui_->alarmStrategyTable->setGridStyle(Qt::SolidLine);

    // 设置表格支持富文本显示
    ui_->alarmStrategyTable->setItemDelegate(new HTMLDelegate(this));
    ui_->alarmStrategyTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

ConfigView::~ConfigView()
{
    delete ui_;
}

void ConfigView::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    // 设置搜索树形控件
    search_tree_->selectRootNode();
    search_tree_->setContextMenuEnabled(true);
    search_tree_->setShortcutEnabled(true);
    search_tree_->setDoubleClickEnabled(true);
    ui_->leftContainer->layout()->addWidget(search_tree_);

    if(state_info_.id() != 0)
    {
        search_tree_->selectNodeByStateInfo(&state_info_);
    }
}

void ConfigView::hideEvent(QHideEvent *event)
{
    QWidget::hideEvent(event);
    search_tree_->setContextMenuEnabled(false);
    search_tree_->setShortcutEnabled(false);
    search_tree_->setDoubleClickEnabled(false);
}

void ConfigView::onNetworkMessageReceived(const QString &method, const QString &body)
{
    if (method == "update-alarm-rules")
    {

        if (body == "success")
        {
            QMessageBox::information(this, "提示", "所有告警规则下装成功");
        }
        else
        {
            QMessageBox::warning(this, "提示", "告警规则下装失败");
        }
    }
}

void ConfigView::onGenerateAlarmStrategyButtonClicked()
{
    // 获取时间间隔
    int interval_secs = ui_->intervalSpin->value();

    // 检查控制帧总数告警策略
    bool control_frame_total_enabled = ui_->controlFrameTotalCheckBox->isChecked();
    int control_frame_total_threshold = ui_->controlFrameTotalSpin->value();
    AlarmLevelEnum control_frame_total_level = AlarmRule::getAlarmLevelFromText(ui_->controlFrameTotalTriggerComboBox->currentText());

    // 检查控制点总数告警策略
    bool control_point_total_enabled = ui_->controlPointTotalCheckBox->isChecked();
    int control_point_total_threshold = ui_->controlPointTotalSpin->value();
    AlarmLevelEnum control_point_total_level = AlarmRule::getAlarmLevelFromText(ui_->controlPointTotalTriggerComboBox->currentText());

    // 检查连续同一地址遥控指令告警策略
    bool same_yk_command_enabled = ui_->sameYkCommandCheckBox->isChecked();
    int same_yk_command_threshold = ui_->sameYkCommandSpin->value();
    AlarmLevelEnum same_yk_command_level = AlarmRule::getAlarmLevelFromText(ui_->sameYkCommandTriggerComboBox->currentText());

    // 检查连续同一地址设点指令告警策略
    bool same_sd_command_enabled = ui_->sameSdCommandCheckBox->isChecked();
    int same_sd_command_threshold = ui_->sameSdCommandSpin->value();
    AlarmLevelEnum same_sd_command_level = AlarmRule::getAlarmLevelFromText(ui_->sameSdCommandTriggerComboBox->currentText());

    // 检查设值的目标值与遥测值相差告警策略
    bool seq_yt_jump_enabled = ui_->seqYtJumpCheckBox->isChecked();
    double seq_yt_jump_threshold = ui_->seqYtJumpSpin->value();
    AlarmLevelEnum seq_yt_jump_level = AlarmRule::getAlarmLevelFromText(ui_->seqYtJumpTriggerComboBox->currentText());

    // 检查遥测值跳变告警策略
    bool seq_yc_jump_enabled = ui_->seqYcJumpCheckBox->isChecked();
    double seq_yc_jump_threshold = ui_->seqYcJumpSpin->value();
    AlarmLevelEnum seq_yc_jump_level = AlarmRule::getAlarmLevelFromText(ui_->seqYcJumpTriggerComboBox->currentText());

    // 创建告警规则列表
    QVector<AlarmRule> alarm_rules;

    // 如果选中了控制帧总数告警策略
    if (control_frame_total_enabled)
    {
        AlarmRule rule(MetricTypeEnum::CONTROL_FRAME_TOTAL, control_frame_total_level, ThresholdUnitEnum::COUNT, state_info_.id());
        rule.setIntervalSecs(interval_secs);
        rule.setThresholdValue(control_frame_total_threshold);
        rule.setEnabled(true);
        alarm_rules.append(rule);
    }

    // 如果选中了控制点总数告警策略
    if (control_point_total_enabled)
    {
        AlarmRule rule(MetricTypeEnum::CONTROL_POINT_TOTAL, control_point_total_level, ThresholdUnitEnum::COUNT, state_info_.id());
        rule.setIntervalSecs(interval_secs);
        rule.setThresholdValue(control_point_total_threshold);
        rule.setEnabled(true);
        alarm_rules.append(rule);
    }

    // 如果选中了连续同一地址遥控指令告警策略
    if (same_yk_command_enabled)
    {
        AlarmRule rule(MetricTypeEnum::SAME_YK_POINT, same_yk_command_level, ThresholdUnitEnum::COUNT, state_info_.id());
        rule.setIntervalSecs(interval_secs);
        rule.setThresholdValue(same_yk_command_threshold);
        rule.setEnabled(true);
        alarm_rules.append(rule);
    }

    // 如果选中了连续同一地址设点指令告警策略
    if (same_sd_command_enabled)
    {
        AlarmRule rule(MetricTypeEnum::SAME_SD_POINT, same_sd_command_level, ThresholdUnitEnum::COUNT, state_info_.id());
        rule.setIntervalSecs(interval_secs);
        rule.setThresholdValue(same_sd_command_threshold);
        rule.setEnabled(true);
        alarm_rules.append(rule);
    }

    // 如果选中了设值的目标值与遥测值相差告警策略
    if (seq_yt_jump_enabled)
    {
        AlarmRule rule(MetricTypeEnum::YT_PRECISION, seq_yt_jump_level, ThresholdUnitEnum::PERCENT, state_info_.id());
        rule.setIntervalSecs(interval_secs);
        rule.setThresholdValue(seq_yt_jump_threshold);
        rule.setEnabled(true);
        alarm_rules.append(rule);
    }

    // 如果选中了遥测值跳变告警策略
    if (seq_yc_jump_enabled)
    {
        AlarmRule rule(MetricTypeEnum::YC_SLOPE, seq_yc_jump_level, ThresholdUnitEnum::PERCENT, state_info_.id());
        rule.setIntervalSecs(interval_secs);
        rule.setThresholdValue(seq_yc_jump_threshold);
        rule.setEnabled(true);
        alarm_rules.append(rule);
    }

    // 尝试将规则插入数据库
    for (const auto &rule : alarm_rules)
    {
        DatabaseManager::insertAlarmRule(rule);
    }

    // 重新加载告警规则
    loadAlarmRules();

    // 刷新UI显示
    renderAlarmRulesToTable();
}

void ConfigView::loadAlarmRules()
{
    // 从本地数据库获取告警规则
    QVector<AlarmRule> alarm_rules = DatabaseManager::queryAllAlarmRules();
    // 清空station_alarm_rules_map_
    station_alarm_rules_map_.clear();

    for (const auto &rule : alarm_rules)
    {
        auto it = station_alarm_rules_map_.find(rule.stateId());
        if (it != station_alarm_rules_map_.end())
        {
            it->second.push_back(rule);
        }
        else
        {
            station_alarm_rules_map_[rule.stateId()] = std::vector<AlarmRule>();
            station_alarm_rules_map_[rule.stateId()].push_back(rule);
        }
    }

    // 使用日志打印station_alarm_rules_map_中的所有数据
    for (const auto &pair : station_alarm_rules_map_)
    {
        int stateId = pair.first;
        const std::vector<AlarmRule> &alarm_rules = pair.second;
        qDebug() << "stateId:" << stateId;
        for (const auto &rule : alarm_rules)
        {
            qDebug() << "rule:" << rule.toPlainText();
        }
    }
}

/**
 * @brief 将告警规则按时间间隔分组并渲染到表格
 */
void ConfigView::renderAlarmRulesToTable()
{
    // 清空表格
    ui_->alarmStrategyTable->setRowCount(0);

    // 获取当前选中变电站的告警规则列表
    auto it = station_alarm_rules_map_.find(state_info_.id());
    if (it == station_alarm_rules_map_.end())
    {
        return;
    }

    const std::vector<AlarmRule> &rules = it->second;

    // 遍历告警规则列表
    for (size_t i = 0; i < rules.size(); ++i)
    {
        const AlarmRule &rule = rules[i];

        // 插入新行
        int row = ui_->alarmStrategyTable->rowCount();
        ui_->alarmStrategyTable->insertRow(row);

        // 设置序号
        QTableWidgetItem *indexItem = new QTableWidgetItem(QString::number(i + 1));
        ui_->alarmStrategyTable->setItem(row, 0, indexItem);

        // 设置策略描述（富文本）
        QTableWidgetItem *descItem = new QTableWidgetItem(rule.toRichText());
        ui_->alarmStrategyTable->setItem(row, 1, descItem);

        // 设置操作按钮
        QPushButton *deleteButton = new QPushButton("删除");
        deleteButton->setObjectName("deleteButton");
        deleteButton->setProperty("row", row);
        deleteButton->setProperty("id", rule.id());
        connect(deleteButton, &QPushButton::clicked, this, &ConfigView::onDeleteAlarmStrategyButtonClicked);
        ui_->alarmStrategyTable->setCellWidget(row, 2, deleteButton);

        // 设置时间间隔（隐藏列）
        QTableWidgetItem *intervalItem = new QTableWidgetItem(QString::number(rule.intervalSecs()));
        ui_->alarmStrategyTable->setItem(row, 3, intervalItem);
    }
}

/**
 * @brief 处理删除告警策略按钮点击
 * @param row 要删除的行号
 */
void ConfigView::onDeleteAlarmStrategyButtonClicked()
{
    // 通过sender获取删除按钮
    QPushButton *deleteButton = qobject_cast<QPushButton *>(sender());
    if (!deleteButton)
    {
        return;
    }
    int id = deleteButton->property("id").toInt();

    DatabaseManager::deleteAlarmRule(id);
    // 重新加载告警规则
    loadAlarmRules();
    // 刷新UI显示
    renderAlarmRulesToTable();
}

void ConfigView::saveAlarmRulesToServer()
{
    // 构建告警规则JSON数组
    QJsonArray rulesArray;
    // 遍历所有变电站的告警规则
    for (const auto &pair : station_alarm_rules_map_)
    {
        int stateId = pair.first;
        const std::vector<AlarmRule> &alarm_rules = pair.second;
        for (const auto &rule : alarm_rules)
        {
            QJsonObject ruleObj;
            ruleObj["stateId"] = rule.stateId();
            ruleObj["metricType"] = static_cast<int>(rule.metricType());
            ruleObj["alarmLevel"] = static_cast<int>(rule.alarmLevel());
            ruleObj["thresholdUnit"] = static_cast<int>(rule.thresholdUnit());
            ruleObj["intervalSecs"] = rule.intervalSecs();
            ruleObj["thresholdValue"] = rule.thresholdValue();
            ruleObj["isEnabled"] = rule.isEnabled();
            rulesArray.append(ruleObj);
        }
    }

    // 发送到服务器
    QJsonDocument doc(rulesArray);
    dealer_handler_->sendRequest("update-alarm-rules", doc.toJson(QJsonDocument::Compact));
}

void ConfigView::onSearchTreeWidgetItemClicked(StateInfo state_info)
{
    state_info_ = state_info;
    // 重新渲染告警规则
    renderAlarmRulesToTable();
}

void ConfigView::onDownloadButtonClicked()
{
    QJsonArray rulesArray;
    // 遍历所有变电站的告警规则
    for (const auto &pair : station_alarm_rules_map_)
    {
        int stateId = pair.first;
        const std::vector<AlarmRule> &alarm_rules = pair.second;

        for (const auto &rule : alarm_rules)
        {
            QJsonObject ruleObj;
            ruleObj["stateId"] = rule.stateId();
            ruleObj["metricType"] = static_cast<int>(rule.metricType());
            ruleObj["alarmLevel"] = static_cast<int>(rule.alarmLevel());
            ruleObj["thresholdUnit"] = static_cast<int>(rule.thresholdUnit());
            ruleObj["intervalSecs"] = rule.intervalSecs();
            ruleObj["thresholdValue"] = rule.thresholdValue();
            ruleObj["isEnabled"] = rule.isEnabled();
            rulesArray.append(ruleObj);
        }
    }

    QJsonDocument doc(rulesArray);
    QString jsonString = doc.toJson(QJsonDocument::Compact);
    dealer_handler_->sendRequest("update-alarm-rules", jsonString);
}

void ConfigView::onAddNodeRequested(int pid, int id)
{
    QVector<AlarmRule> rules = DatabaseManager::queryAlarmRules(pid);
    // 插入新站规则
    for (AlarmRule rule : rules)
    {
        rule.setStateId(id);
        DatabaseManager::insertAlarmRule(rule);
    }
    if (rules.size() > 0)
    {
        // 重新加载告警规则
        loadAlarmRules();
        qDebug() << "新站的告警规则已经根据所属主站生成";
    }
}
